/**
 * 主JavaScript文件
 * 负责应用程序的核心功能和与Tauri后端的通信
 */

// 确保 Tauri API 已加载
let invoke, listen, appWindow;

function initializeTauriAPI() {
  try {
    if (window.__TAURI__) {
      invoke = window.__TAURI__.invoke;
      listen = window.__TAURI__.event.listen;
      appWindow = window.__TAURI__.window.appWindow;
      console.log('Tauri API 组件已初始化');
      return true;
    }
    console.warn('Tauri API 尚未加载');
    return false;
  } catch (error) {
    console.error('初始化Tauri API时发生错误:', error);
    return false;
  }
}

// 等待 Tauri API 加载完成
const waitForTauriAPI = () => {
  return new Promise((resolve, reject) => {
    if (initializeTauriAPI()) {
      resolve();
    } else {
      const checkInterval = setInterval(() => {
        if (initializeTauriAPI()) {
          clearInterval(checkInterval);
          resolve();
        }
      }, 50);

      // 设置超时
      setTimeout(() => {
        clearInterval(checkInterval);
        reject(new Error('Tauri API 加载超时'));
      }, 5000);
    }
  });
};

// MinuteTrading 会在其自己的文件中定义为全局变量

// 主窗口加载完成时的处理
window.addEventListener('load', async () => {
  console.log('Main window loaded');
  try {
    await waitForTauriAPI();
    console.log('Tauri API 初始化成功');
  } catch (error) {
    console.error('Tauri API 初始化失败:', error);
  }
});
 
// 应用程序初始化
document.addEventListener('DOMContentLoaded', () => {
  // 初始化UI组件
  initializeUI();
  
  // 设置全局事件监听器
  setupEventListeners();
  
  // 检查Python环境
  checkPythonEnvironment();
  
  // 初始化分钟交易模块
  if (document.getElementById('minute-chart')) {
    window.minuteTrading = new MinuteTrading();
  }
});

/**
 * 初始化UI组件
 */
function initializeUI() {
  // 创建加载指示器
  createLoadingIndicator();
  
  // 创建通知容器
  createToastContainer();
  
  // 初始化模态框
  initModals();
}

/**
 * 创建加载指示器
 */
function createLoadingIndicator() {
  const loadingIndicator = document.createElement('div');
  loadingIndicator.id = 'loading-indicator';
  loadingIndicator.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
  loadingIndicator.style.display = 'none';
  
  loadingIndicator.innerHTML = `
    <div class="bg-white p-5 rounded-lg shadow-lg flex items-center">
      <svg class="animate-spin h-6 w-6 text-blue-500 mr-3" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
      </svg>
      <span class="text-gray-700 font-medium">处理中...</span>
    </div>
  `;
  
  document.body.appendChild(loadingIndicator);
}

/**
 * 创建通知容器
 */
function createToastContainer() {
  const toastContainer = document.createElement('div');
  toastContainer.id = 'toast-container';
  toastContainer.className = 'fixed bottom-4 right-4 z-50';
  document.body.appendChild(toastContainer);
}

/**
 * 初始化模态框
 */
function initModals() {
  // 创建模态框容器
  const modalContainer = document.createElement('div');
  modalContainer.id = 'modal-container';
  document.body.appendChild(modalContainer);
}

/**
 * 设置全局事件监听器
 */
function setupEventListeners() {
  // 运行测试按钮
  const runTestButton = document.querySelector('button[data-action="run-test"]');
  if (runTestButton) {
    runTestButton.addEventListener('click', () => run_investment());
  }
  
  // 清空结果按钮
  const clearResultButton = document.querySelector('button[data-action="clear-result"]');
  if (clearResultButton) {
    clearResultButton.addEventListener('click', () => clear_playwright_result());
  }
  
  // 设置全局错误处理
  window.addEventListener('error', (event) => {
    console.error('全局错误:', event.error);
    showToast(`发生错误: ${event.error.message || '未知错误'}`, 'error');
  });
  
  // 设置未处理的Promise拒绝处理
  window.addEventListener('unhandledrejection', (event) => {
    console.error('未处理的Promise拒绝:', event.reason);
    showToast(`Promise错误: ${event.reason.message || '未知错误'}`, 'error');
  });
}

/**
 * 检查Python环境
 */
async function checkPythonEnvironment() {
  try {
    showLoadingIndicator();
    
    // 等待Tauri API初始化
    try {
      await waitForTauriAPI();
    } catch (error) {
      console.warn('等待Tauri API超时，尝试降级模式');
      hideLoadingIndicator();
      showToast('系统正在降级模式运行', 'warning');
      return;
    }
    
    // 确保invoke已定义
    if (typeof invoke === 'function') {
      try {
        const status = await invoke('check_python_environment');
        console.log('Python环境状态:', status);
        
        if (status.ready) {
          console.log('Python环境已就绪');
          showToast('Python环境检查完成', 'success');
        } else {
          console.log('Python环境需要设置');
          showPythonSetupModal(status);
        }
      } catch (invokeError) {
        console.error('调用Python环境检查失败:', invokeError);
        showToast('Python环境检查失败: ' + (invokeError.message || '未知错误'), 'error');
      }
    } else {
      console.error('Tauri API未初始化，无法检查Python环境');
      showToast('无法检查Python环境: Tauri API未初始化', 'error');
    }
  } catch (error) {
    console.error('检查Python环境时发生错误:', error);
    showToast('环境检查失败: ' + (error.message || '未知错误'), 'error');
  } finally {
    hideLoadingIndicator();
  }
}

/**
 * 显示Python设置模态框
 * @param {Object} status - Python环境状态
 */
function showPythonSetupModal(status) {
  const modalContainer = document.getElementById('modal-container');
  if (!modalContainer) return;
  
  const modal = document.createElement('div');
  modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
  modal.innerHTML = `
    <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
      <div class="p-6">
        <h2 class="text-xl font-semibold mb-4">Python环境设置</h2>
        <div class="space-y-4">
          <div class="flex items-start">
            <div class="flex-shrink-0">
              <svg class="h-6 w-6 text-yellow-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
              </svg>
            </div>
            <div class="ml-3">
              <p class="text-gray-700">${status.message || '需要设置Python环境才能使用所有功能。'}</p>
            </div>
          </div>
          <div class="space-y-2">
            <p class="font-medium text-gray-900">环境要求：</p>
            <ul class="list-disc pl-5 space-y-1 text-gray-600">
              <li>已安装 Python 3.x</li>
              <li>已安装必要的依赖包（numpy, pandas, scikit-learn等）</li>
            </ul>
          </div>
          <div class="mt-6 flex justify-end space-x-3">
            <button class="px-4 py-2 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors" onclick="closeModal(this)">
              取消
            </button>
            <button class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors" onclick="setupPythonEnvironment()">
              开始设置
            </button>
          </div>
        </div>
      </div>
    </div>
  `;
  
  modalContainer.innerHTML = '';
  modalContainer.appendChild(modal);
}

/**
 * 关闭模态框
 */
function closeModal(button) {
  const modal = button.closest('.fixed');
  if (modal) {
    modal.remove();
  }
}

/**
 * 设置Python环境
 */
async function setupPythonEnvironment() {
  try {
    showLoadingIndicator();
    await invoke('setup_python_environment');
    hideLoadingIndicator();
    showToast('Python环境设置完成', 'success');
    closeModal(document.querySelector('.modal button'));
    
    // 重新检查环境
    await checkPythonEnvironment();
  } catch (error) {
    hideLoadingIndicator();
    console.error('设置Python环境失败:', error);
    showToast(`设置失败: ${error}`, 'error');
  }
}

/**
 * 显示加载指示器
 */
function showLoadingIndicator() {
  const loadingIndicator = document.getElementById('loading-indicator');
  if (loadingIndicator) {
    loadingIndicator.style.display = 'flex';
  }
}

/**
 * 隐藏加载指示器
 */
function hideLoadingIndicator() {
  const loadingIndicator = document.getElementById('loading-indicator');
  if (loadingIndicator) {
    loadingIndicator.style.display = 'none';
  }
}

/**
 * 显示Python环境设置模态框
 * @param {Object} status - Python环境状态
 */
function showPythonSetupModal(status) {
  const modal = document.getElementById('python-setup-modal');
  if (modal) {
    modal.style.display = 'block';
  }
}

/**
 * 运行投资测试
 */
async function run_investment() {
  try {
    // 显示加载状态
    document.dispatchEvent(new CustomEvent('playwright-started'));
    
    // 清空结果
    clear_playwright_result();
    
    // 添加开始消息
    appendPlaywrightResult('开始运行投资测试...');
    
    // 调用后端API
    const result = await invoke('run_investment');
    
    // 处理结果
    if (result && result.logs) {
      result.logs.forEach(log => {
        appendPlaywrightResult(log);
      });
    }
    
    // 添加完成消息
    appendPlaywrightResult('测试完成', 'success');
  } catch (error) {
    console.error('运行投资测试失败:', error);
    appendPlaywrightResult(`错误: ${error.message || '未知错误'}`, 'error');
  } finally {
    // 隐藏加载状态
    document.dispatchEvent(new CustomEvent('playwright-finished'));
  }
}

/**
 * 清空Playwright结果
 */
function clear_playwright_result() {
  const resultElement = document.getElementById('playwright-result');
  if (resultElement) {
    resultElement.innerHTML = '';
  }
}

/**
 * 添加Playwright结果
 * @param {string} message - 消息内容
 * @param {string} type - 消息类型 (info, success, warning, error)
 */
function appendPlaywrightResult(message, type = 'info') {
  const resultElement = document.getElementById('playwright-result');
  if (!resultElement) return;
  
  const item = document.createElement('li');
  item.className = 'py-1';
  
  // 根据类型设置样式和图标
  switch (type) {
    case 'success':
      item.className += ' text-green-600';
      item.innerHTML = `<span class="mr-2">✅</span>${message}`;
      break;
    case 'warning':
      item.className += ' text-yellow-600';
      item.innerHTML = `<span class="mr-2">⚠️</span>${message}`;
      break;
    case 'error':
      item.className += ' text-red-600';
      item.innerHTML = `<span class="mr-2">❌</span>${message}`;
      break;
    default:
      item.className += ' text-gray-600';
      item.innerHTML = `<span class="mr-2">ℹ️</span>${message}`;
  }
  
  resultElement.appendChild(item);
  
  // 滚动到底部
  resultElement.scrollTop = resultElement.scrollHeight;
}

/**
 * 显示通知提示
 * @param {string} message - 提示消息
 * @param {string} type - 提示类型 (success, error, warning, info)
 */
function showToast(message, type = 'info') {
  const toastContainer = document.getElementById('toast-container');
  if (!toastContainer) return;
  
  const toast = document.createElement('div');
  toast.className = `toast toast-${type} mb-2 transform translate-y-2 opacity-0 transition-all duration-300`;
  
  // 设置图标
  let icon = '';
  switch (type) {
    case 'success':
      icon = '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>';
      break;
    case 'error':
      icon = '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>';
      break;
    case 'warning':
      icon = '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg>';
      break;
    default:
      icon = '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>';
  }
  
  toast.innerHTML = `
    <div class="flex items-center">
      <span class="mr-2">${icon}</span>
      <span>${message}</span>
    </div>
  `;
  
  toastContainer.appendChild(toast);
  
  // 显示动画
  setTimeout(() => {
    toast.classList.remove('translate-y-2', 'opacity-0');
  }, 10);
  
  // 自动关闭
  setTimeout(() => {
    toast.classList.add('translate-y-2', 'opacity-0');
    setTimeout(() => {
      toast.remove();
    }, 300);
  }, 3000);
}

// 导出全局函数
window.run_investment = run_investment;
window.clear_playwright_result = clear_playwright_result;
window.appendPlaywrightResult = appendPlaywrightResult;
window.showToast = showToast;